"""
简化的日志配置模块
"""
import logging
import time
from pathlib import Path
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware


class RequestLoggingMiddleware(BaseHTTPMiddleware):
    """简化的请求日志中间件"""
    
    def __init__(self, app):
        super().__init__(app)
        self.logger = logging.getLogger("request")
    
    async def dispatch(self, request: Request, call_next):
        start_time = time.time()
        
        try:
            response = await call_next(request)
            process_time = time.time() - start_time
            
            self.logger.info(
                f"{request.method} {request.url.path} - "
                f"{response.status_code} - {process_time:.3f}s"
            )
            
            return response
            
        except Exception as e:
            process_time = time.time() - start_time
            self.logger.error(
                f"{request.method} {request.url.path} - "
                f"ERROR: {str(e)} - {process_time:.3f}s"
            )
            raise


def setup_logging(log_level: str = "INFO"):
    """设置简化的日志配置"""
    # 创建日志目录
    Path("logs").mkdir(exist_ok=True)
    
    # 基础配置
    logging.basicConfig(
        level=getattr(logging, log_level.upper()),
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler("logs/app.log", encoding="utf-8"),
            logging.StreamHandler()
        ]
    )
    
    # 第三方库日志级别
    logging.getLogger("uvicorn").setLevel(logging.WARNING)
    logging.getLogger("httpx").setLevel(logging.WARNING)